package com.jinlia.show.modules.base.config.bean;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.util.StringUtils;

import java.io.File;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;

/**
 * 注意TableName注解 加autoResultMap = true
 */
public class MybatisBaseTypeHandler extends BaseTypeHandler<String> {

    /**
     * 项目启动后注入环境变量
     */
    public static String fileUrl;
    //文件扩展名校验
    private List<String> tableFieldValues = Arrays.asList(
            "img_url","imgUrl",
            "cover_img","coverImg",
            "content_img","contentImg",
            "detail_img","detailImg",
            "goods_pics","goodsPics",
            "attr_value_pics","attrValuePics");
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter);
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        if (!StringUtils.hasLength(rs.getString(columnName))) {
            return null;
        }
        if (tableFieldValues.contains(columnName)) {
            StringBuilder sb = new StringBuilder();
            String[] split = rs.getString(columnName).split(",");
            for (String filePathName : split) {
                if (sb.length() > 0) {
                    sb.append(",");
                }
                if (filePathName.startsWith("http")) {
                    sb.append(filePathName);
                }else {
                    //支持多级路径
                    if (filePathName.contains("_")) {
                        filePathName = filePathName.replaceAll("_", Matcher.quoteReplacement(java.io.File.separator));
//                        filePathName = filePathName.replaceAll("_", File.separator);
                    }
                    sb.append(fileUrl).append(filePathName);
                }

            }
            return sb.toString();
        } else {
            return rs.getString(columnName);
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return rs.getString(columnIndex);
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return cs.getString(columnIndex);
    }
}
